$(function () {
    var unixTimeToDateString = function (ts, ex) {
        ts = parseFloat(ts) || 0;
        if (ts < 1) {
            return '';
        }
        var d = new Date();
        d.setTime(ts * 1e3);
        var s = '' + d.getFullYear() + '-' + (1 + d.getMonth()) + '-' + d.getDate();
        if (ex) {
            s += ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
        }
        return s;
    };

    var buyLimitation = function (a, b) {
        a = parseInt(a) || 0;
        b = parseInt(b) || 0;
        var r = 0;
        if (a > 0) {
            r = a;
        }
        if (b > 0 && r > 0 && b < r) {
            r = b;
        }
        return r;
    };

    template.helper('isEmpty', function (o) {
        for (var i in o) {
            return false;
        }
        return true;
    });

    // 图片轮播
    function picSwipe() {
        var elem = $("#mySwipe")[0];
        window.mySwipe = Swipe(elem, {
            continuous: false,
            // disableScroll: true,
            stopPropagation: true,
            callback: function (index, element) {
                $(".goods-detail-turn").find("li").eq(e).addClass("cur").siblings().removeClass("cur")
            }
        });
    }
    var goods_id = GetQueryString("goods_id");
    var goodsData = {};
    var colorIsShow = false;
    var buyType = '';

    //渲染页面
    $.ajax({
        url: ApiUrl + "/user/eb/getCommodity/"+goods_id,
        type: "post",
        data:"isDetail=true",
        dataType: "json",
        success: function (data) {
            console.log(data);
            var storage = 100;
            if (!data.rspCode) {
                $('#detail').html(data.commodity.content)
                //渲染模板
                if(data.commodity.carouselPhoto){
                  var goods_image = data.commodity.carouselPhoto.split(",");
                  data.goods_image = goods_image;
                }else{
                   data.goods_image = [];
                }
                //渲染模板
                var html = template.render('product_top', data);
                $("#product_detail_wp").html(html);
                //图片轮播
                picSwipe();

                var myData = {};                
                // $('.choose-color li').eq(0).click();

                if(data.packages[0].advanceMoney)
                    $(".add-to-cart").hide();
                //加入购物车
                $(".add-to-cart").click(function () {
                    // var quantity = parseInt($(".buy-num").val());
                    if (colorIsShow==false) {
                        $.sDialog({
                            skin: "",
                            content:template.render('product_detail', data),
                            width:parseInt($(window).width()),
                            okBtn: false,
                            cancelBtn: true,
                            cancelBtnText:'<i class="fa fa-fw fa-close"  aria-hidde="true"></i>关闭',
                            cancelFn: function() {
                                colorIsShow = false;
                                $('.opera-product-wpq').show();
                                $('#sure-buy').hide();
                                $('body').css('overflow','auto');
                            } 
                        });
                        //购买数量，减
                        $(".minus-wp").click(function () {
                            var index = $('.choose-color li.current').index();
                            var buynum = parseInt($(".buy-num").val());
                            if (buynum > 1) {
                                $(".buy-num").val(parseInt(buynum - 1));
                                if(data.packages[index].advanceMoney)
                                    $('#cat-price').text(data.packages[index].advanceMoney*(buynum - 1));
                                else
                                    $('#cat-price').text(data.packages[index].money*(buynum - 1));
                            }
                        });
                        //购买数量加
                        $(".add-wp").click(function () {
                            var index = $('.choose-color li.current').index();
                            var buynum = parseInt($(".buy-num").val());
                            if (buynum < storage) {
                                $(".buy-num").val(parseInt(buynum + 1));
                                if(data.packages[index].advanceMoney)
                                    $('#cat-price').text(data.packages[index].advanceMoney*(buynum + 1));
                                else
                                    $('#cat-price').text(data.packages[index].money*(buynum + 1));
                            }

                        });
                        $('.choose-color li').click(function(){
                            $('.choose-color li.current').removeClass('current');
                            $(this).addClass('current');
                            var index = $(this).index();
                            var buynum = parseInt($(".buy-num").val());
                            storage =parseInt(data.packages[index].repertory);
                            if(data.packages[index].advanceMoney)
                                $('#cat-price').text(data.packages[index].advanceMoney*buynum);
                            else
                                $('#cat-price').text(data.packages[index].money*buynum);
                        });
                        $('.opera-product-wpq').hide();
                        $('#sure-buy').show();
                        colorIsShow = true;
                        $('body').css('overflow','hidden');
                        buyType = 'add-to-cart';
                        return false;
                    };
                });

                //立即购买
                $(".buy-now").click(function () {

                    if (colorIsShow==false) {
                        $.sDialog({
                            skin: "",
                            content:template.render('product_detail', data),
                            width:parseInt($(window).width()),
                            okBtn: false,
                            cancelBtn: true,
                            cancelBtnText:'<i class="fa fa-fw fa-close"  aria-hidde="true"></i>关闭',
                            cancelFn: function() {
                                colorIsShow = false;
                                $('.opera-product-wpq').show();
                                $('#sure-buy').hide();
                                $('body').css('overflow','auto');
                            } 
                        });
                        //购买数量，减
                        $(".minus-wp").click(function () {
                            var index = $('.choose-color li.current').index();
                            var buynum = parseInt($(".buy-num").val());
                            if (buynum > 1) {
                                $(".buy-num").val(parseInt(buynum - 1));
                                if(data.packages[index].advanceMoney)
                                    $('#cat-price').text(data.packages[index].advanceMoney*(buynum - 1));
                                else
                                    $('#cat-price').text(data.packages[index].money*(buynum - 1));
                            }
                        });
                        //购买数量加
                        $(".add-wp").click(function () {
                            var index = $('.choose-color li.current').index();
                            var buynum = parseInt($(".buy-num").val());
                            if (buynum < storage) {
                                $(".buy-num").val(parseInt(buynum + 1));
                                if(data.packages[index].advanceMoney)
                                    $('#cat-price').text(data.packages[index].advanceMoney*(buynum + 1));
                                else
                                    $('#cat-price').text(data.packages[index].money*(buynum + 1));
                            }

                        });





                        $('.choose-color li').click(function(){
                            $('.choose-color li.current').removeClass('current');
                            $(this).addClass('current');
                            var index = $(this).index();
                            storage =parseInt(data.packages[index].repertory);
                            var buynum = parseInt($('.buy-num').val());
                            if(data.packages[index].advanceMoney)
                                $('#cat-price').text(data.packages[index].advanceMoney*buynum);
                            else
                                $('#cat-price').text(data.packages[index].money*buynum);
                        });
                        $('.opera-product-wpq').hide();
                        $('#sure-buy').show();
                        colorIsShow = true;
                        buyType = 'buy-now';
                        $('body').css('overflow','hidden');
                        return false;
                    };
                    // }
                });
                $("#sure-buy").click(function () {
                    if ($('.choose-color li.current').length<=0) {
                        return false;
                    };
                    if (buyType == 'buy-now') {
                        var carts = [];
                        var cart = {};
                        var cpackage = {};
                        cpackage.id = $('.choose-color li.current').attr('data-id');
                        cart.cpackage = cpackage;
                        cart.num = parseInt($('.buy-num').val());;
                        carts.push(cart);
                        $.ajax({
                            url: ApiUrl + "/user/eb/saveOrder",
                            type: "post",
                            contentType: "application/json",
                            data: JSON.stringify(carts),
                            dataType: "json",
                            success: function (res) {
                                checklogin(res.rspCode);
                                // if (checklogin(res.login)) {
                                if (res.rspCode==0) {
                                    window.location.href = WapSiteUrl + "/tmpl/order/buy_step1.html?ifcart=1&cart_id="+res.orderId;
                                } else {
                                    $.sDialog({
                                        skin: "red",
                                        content: res.rspDesc,
                                        okBtn: false,
                                        cancelBtn: false
                                    });
                                }
                                // }
                            }
                        });
                    }else{
                        $.ajax({                        
                            url:ApiUrl + "/user/eb/addShoppingCart/"+$('.choose-color li.current').attr('data-id'),
                            type: "post",
                            dataType: "json",
                            success: function (result) {
                                // checklogin(result.rspCode);
                                if (result.rspCode==0) {
                                     window.location.href = WapSiteUrl + '/tmpl/cart_list.html';
                                } else {
                                   
                                };
                            }
                        });
                    };
                })

            } else {

                $.sDialog({
                    content: data.error + '！<br>请返回上一页继续操作…',
                    okBtn: false,
                    cancelBtnText: '返回',
                    cancelFn: function () {
                        history.back();
                    }
                });

                //var html = data.error;
                //$("#product_detail_wp").html(html);

            }

            //验证购买数量是不是数字
            $("#buynum").blur(buyNumer);
            // AddView();
        }


    });
    //点击商品规格，获取新的商品
    function arrowClick(self, myData) {
        $(self).addClass("current").siblings().removeClass("current");
        //拼接属性
        var curEle = $(".pddc-stock-spec").find("a.current");
        var curSpec = [];
        $.each(curEle, function (i, v) {
            curSpec.push($(v).attr("specs_value_id"));
        });
        var spec_string = curSpec.sort().join("|");
        //获取商品ID
        var spec_goods_id = myData.spec_list[spec_string];
        window.location.href = "product_detail.html?goods_id=" + spec_goods_id;
    }

    function AddView() {//增加浏览记录
        var goods_info = getcookie('goods');
        var goods_id = GetQueryString('goods_id');
        if (goods_id < 1) {
            return false;
        }

        if (goods_info == '') {
            goods_info += goods_id;
        } else {

            var goodsarr = goods_info.split('@');
            if (contains(goodsarr, goods_id)) {
                return false;
            }
            if (goodsarr.length < 5) {
                goods_info += '@' + goods_id;
            } else {
                goodsarr.splice(0, 1);
                goodsarr.push(goods_id);
                goods_info = goodsarr.join('@');
            }
        }

        addcookie('goods', goods_info);
        return false;
    }

    function contains(arr, str) {//检测goods_id是否存入
        var i = arr.length;
        while (i--) {
            if (arr[i] === str) {
                return true;
            }
        }
        return false;
    }

    $.sValid.init({
        rules: {
            buynum: "digits"
        },
        messages: {
            buynum: "请输入正确的数字"
        },
        callback: function (eId, eMsg, eRules) {
            if (eId.length > 0) {
                var errorHtml = "";
                $.map(eMsg, function (idx, item) {
                    errorHtml += "<p>" + idx + "</p>";
                });
                $.sDialog({
                    skin: "red",
                    content: errorHtml,
                    okBtn: false,
                    cancelBtn: false
                });
            }
        }
    });
    //检测商品数目是否为正整数
    function buyNumer() {
        $.sValid();
    }
});